#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>

int main (void)
{
    int  n               = 25;
    char szBuff[25 + 1]  = {0};
    
    HANDLE         hSerial;
    DCB            dcbSerialParams = {0};
    COMMTIMEOUTS   timeouts        = {0};
    DWORD          dwBytesRead     = 25;
    
    dcbSerialParams.DCBlength      = sizeof(DCB);

    hSerial = CreateFile("COM16",
                     GENERIC_READ | GENERIC_WRITE,
                     0,
                     0,
                     OPEN_EXISTING,
                     FILE_ATTRIBUTE_NORMAL,
                     0);
    
    
    if(hSerial == INVALID_HANDLE_VALUE){
      if(GetLastError() == ERROR_FILE_NOT_FOUND){
        puts ("cannot open port!");
      }
      puts ("invalid handle value!");               
    }
    
    if (!GetCommState(hSerial, &dcbSerialParams)) {
      puts ("error getting state");
    }
    
    dcbSerialParams.BaudRate  = CBR_9600;
    dcbSerialParams.ByteSize  = 255;
    dcbSerialParams.StopBits  = ONESTOPBIT;
    dcbSerialParams.Parity    = NOPARITY;
    
   if(!SetCommState(hSerial, &dcbSerialParams)){
      puts ("error setting port state");
   }
    
   timeouts.ReadIntervalTimeout         = 30;
   timeouts.ReadTotalTimeoutMultiplier  = 100;
   timeouts.ReadTotalTimeoutConstant    = 100;
   system("PAUSE");    
   if (!SetCommTimeouts(hSerial, &timeouts)){
      puts ("timeouts setting fail!");
   }
    
   //while (1){      
 
	// Espera entrada de valores em COM    
	   if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
		  puts ("serial read error fail!");
	   } else {        
		  printf ("%s\n" , szBuff);
	   }
	   
   //}
   system("PAUSE");
   return 0;
}

